package com.shm.controller;

import java.util.List;
import javax.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.common.core.domain.entity.Follow;
import com.ruoyi.common.core.domain.entity.Product;
import com.ruoyi.common.core.domain.entity.Star;
import com.ruoyi.common.enums.ErrorCode;
import com.ruoyi.common.exception.ServiceException;
import com.shm.service.IProductService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.shm.service.IStarService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 收藏Controller
 *
 * @author dam
 * @date 2023-08-09
 */
@RestController
@RequestMapping("/market/star")
public class StarController extends BaseController {
    @Autowired
    private IStarService starService;
    @Autowired
    private IProductService productService;

    /**
     * 查询收藏列表
     */
    @PreAuthorize("@ss.hasPermi('market:star:list')")
    @GetMapping("/list")
    public TableDataInfo list(Star star) {
        startPage();
        List<Star> list = starService.list(new QueryWrapper<Star>(star));
        return getDataTable(list);
    }

    /**
     * 导出收藏列表
     */
    @PreAuthorize("@ss.hasPermi('market:star:export')")
    @Log(title = "收藏", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Star star) {
        List<Star> list = starService.list(new QueryWrapper<Star>(star));
        ExcelUtil<Star> util = new ExcelUtil<Star>(Star.class);
        util.exportExcel(response, list, "收藏数据");
    }

    /**
     * 获取收藏详细信息
     */
    @PreAuthorize("@ss.hasPermi('market:star:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(starService.getById(id));
    }

    /**
     * 新增收藏
     */
    @PreAuthorize("@ss.hasPermi('market:star:add')")
    @Log(title = "收藏", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Star star) {
        return toAjax(starService.save(star));
    }

    /**
     * 修改收藏
     */
    @PreAuthorize("@ss.hasPermi('market:star:edit')")
    @Log(title = "收藏", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Star star) {
        return toAjax(starService.updateById(star));
    }

    /**
     * 删除收藏
     */
    @PreAuthorize("@ss.hasPermi('market:star:remove')")
    @Log(title = "收藏", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable List<Long> ids) {
        return toAjax(starService.removeByIds(ids));
    }

    /**
     * 收藏商品
     */
    @PreAuthorize("@ss.hasPermi('market:star:star')")
    @GetMapping("/starProduct/{productId}")
    public AjaxResult starProduct(@PathVariable("productId") Long productId) {
        Star star = new Star();
        star.setUserId(getLoginUser().getUserId());
        star.setProductId(productId);
        Product product = productService.getById(productId);
        if (product.getUserId().equals(getLoginUser().getUserId())) {
            throw new ServiceException("自己不能收藏自己的商品", ErrorCode.OPERATION_ERROR.getCode());
        }
        boolean isStar = starService.addStar(star);
        if (isStar) {
            // 需要将商品的收藏量+1
            productService.starNumPlusOne(productId);
        }
        return AjaxResult.success();
    }

    /**
     * 查询是否已经收藏商品
     */
    @PreAuthorize("@ss.hasPermi('market:star:query')")
    @GetMapping("/hadStar/{productId}")
    public AjaxResult hadStar(@PathVariable("productId") Long productId) {
        QueryWrapper<Star> followQueryWrapper = new QueryWrapper<Star>();
        followQueryWrapper.eq("user_id", getLoginUser().getUserId());
        followQueryWrapper.eq("product_id", productId);
        Star one = starService.getOne(followQueryWrapper);
        return AjaxResult.success().put("hadStar", one != null ? true : false);
    }

    /**
     * 取消收藏商品
     */
    @PreAuthorize("@ss.hasPermi('market:star:cancelStar')")
    @Log(title = "取消关注", businessType = BusinessType.DELETE)
    @GetMapping("/cancelStar/{productId}")
    public AjaxResult cancelStar(@PathVariable("productId") Long productId) {
        QueryWrapper<Star> followQueryWrapper = new QueryWrapper<Star>();
        followQueryWrapper.eq("user_id", getLoginUser().getUserId());
        followQueryWrapper.eq("product_id", productId);
        boolean remove = starService.remove(followQueryWrapper);
        if (remove) {
            // 需要将商品的收藏量-1
            productService.starNumDiffOne(productId);
        }
        return AjaxResult.success();
    }
}
